package com.hemaapp.yjnh.activity;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.util.XtomWindowSize;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseFragmentActivity;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.FarmerCropDetailAdapter;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.BlogDetail;
import com.hemaapp.yjnh.bean.ClientDetails;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.ImgItemsBean;
import com.hemaapp.yjnh.bean.Reply;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.listener.OnJournalClickListener;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.utils.LoginUtil;
import com.hemaapp.yjnh.view.ImageCarouselBanner;
import com.hemaapp.yjnh.view.ShareDialog;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.media.UMImage;

/** 农家的农货商品详情
 * @author GuiyouZhang
 * 创建时间：2015年9月28日 下午3:25:04
 * 最后修改时间：2015年9月28日 下午3:25:04
 */
public class FarmerCropDetailActivity extends BaseFragmentActivity implements OnClickListener{

    @Bind(R.id.image_carousel_banner)
    ImageCarouselBanner imageCarouselBanner;
	@Bind(R.id.tv_A)
	TextView tvA;
	@Bind(R.id.tv_organic)
	TextView tvOrganic;
	@Bind(R.id.layout_head)
	FrameLayout layoutHead;
	@Bind(R.id.tv_goods_name)
	TextView tvGoodsName;
	@Bind(R.id.tv_price_new)
	TextView tvPriceNew;
    @Bind(R.id.tv_price_old)
    TextView tvPriceOld;
	@Bind(R.id.tv_coupons_count)
	TextView tvCouponsCount;
	@Bind(R.id.tv_assort)
	TextView tvAssort;
    @Bind(R.id.tv_freight)
    TextView tvFreight;
	@Bind(R.id.tv_unit)
	TextView tvUnit;
	@Bind(R.id.tv_sell_count)
	TextView tvSellCount;
    @Bind(R.id.tv_tuihuo)
    TextView tvTuihuo;
	@Bind(R.id.iv_merchant_avatar)
	ImageView ivMerchantAvatar;
	@Bind(R.id.tv_merchant_name)
	TextView tvMerchantName;
    @Bind(R.id.ratingBar)
    RatingBar ratingBar;
	@Bind(R.id.tv_merchant_address)
	TextView tvMerchantAddress;
	@Bind(R.id.iv_phone)
	ImageView ivPhone;
	@Bind(R.id.layout_merchant)
	LinearLayout layoutMerchant;
//	@Bind(R.id.tv_detail)
//	TextView tvDetail;
	@Bind(R.id.line_detail)
	View lineDetail;
	@Bind(R.id.layout_detail)
	RelativeLayout layoutDetail;
//	@Bind(R.id.tv_journal)
//	TextView tvJournal;
	@Bind(R.id.line_journal)
	View lineJournal;
	@Bind(R.id.layout_journal)
	RelativeLayout layoutJournal;
//	@Bind(R.id.tv_reply)
//	TextView tvReply;
	@Bind(R.id.line_reply)
	View lineReply;
	@Bind(R.id.layout_reply)
	RelativeLayout layoutReply;
	private TextView titleText;
	private ImageButton titleLeft;
	private Button titleRightBtn;
	private ImageView titleShare;
	private ImageView titleLove;

    private XtomRefreshLoadmoreLayout refreshlayout;
    private XtomListView listView;
    private TextView tvCustomize;
    private View headerView;
    private View headerView2;
    private TextView tvPackage;
    private TextView tvSpec;

	private String blog_id;//当前商品的id
	private BlogDetail blog;//当前商品信息
    private LoginUtil.LoginCallBack loginCallBack;
    private ClientDetails client;
    private ArrayList<ImgItemsBean> detailsImg = new ArrayList<>();//详情图片
    private ArrayList<Reply> replies= new ArrayList<>();
    private ArrayList<Blog> journals= new ArrayList<>();//农货对应的日志列表
    private FarmerCropDetailAdapter adapter;
    private User user;
    private int replyPage = 0;//评论的页数
    private int jouralPage = 0;//日志的页数
    private int type = 1;//1商品详情，2评论, 3日志
	private Blog selJournal;//当前操作的日志，用于对日志进行了点赞等操作
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_customize_production_detail);
		user = getApplicationContext().getUser();
		super.onCreate(savedInstanceState);
		EventBus.getDefault().register(this);
		init();
        if (!blog_id.equals("0")) {
            String token = user == null?"":user.getToken();
            getNetWorker().getBlogDetail(token, blog_id);
        }
	}

	@Override
	public void onDestroy() {
		EventBus.getDefault().unregister(this);
		super.onDestroy();
	}

	private void init() {
        //给listview加header
        headerView = LayoutInflater.from(mContext).inflate(R.layout.header_farmer_crop_detail, null);
        ButterKnife.bind(this, headerView);
        int screenWidth = getWindowManager().getDefaultDisplay().getWidth(); // 屏幕宽（像素）
        layoutHead.getLayoutParams().height = screenWidth;
        ivPhone.setOnClickListener(this);
        layoutDetail.setOnClickListener(this);
        layoutJournal.setOnClickListener(this);
        layoutReply.setOnClickListener(this);
        layoutMerchant.setOnClickListener(this);
        headerView2 = LayoutInflater.from(mContext).inflate(R.layout.header_customize_detail2, null);
        tvPackage = (TextView) headerView2.findViewById(R.id.tv_package);
        tvSpec = (TextView) headerView2.findViewById(R.id.tv_spec);
	}

    @Override
    protected void getExras() {
        blog_id = mIntent.getStringExtra("blog_id");
    }

    @Override
    protected void findView() {
        titleText = (TextView) findViewById(R.id.title_text);
        titleLeft = (ImageButton) findViewById(R.id.title_left_btn);
        titleRightBtn = (Button) findViewById(R.id.title_right_btn);
        titleLove = (ImageView) findViewById(R.id.title_right_img);
        titleShare = (ImageView) findViewById(R.id.title_right_img2);

        refreshlayout = (XtomRefreshLoadmoreLayout) findViewById(R.id.refreshLoadmoreLayout);
        listView = (XtomListView) findViewById(R.id.listview);
        listView.setFocusable(false);
        tvCustomize = (TextView) findViewById(R.id.tv_customize);
    }

    private void initImagePager() {
        ArrayList<String> urls = new ArrayList<>();
        for (ImgItemsBean item : blog.getImgItems()) {
            urls.add(item.getImgurlbig());
        }
        imageCarouselBanner.getLayoutParams().height = XtomWindowSize.getWidth(mContext);
        layoutHead.getLayoutParams().height = XtomWindowSize.getWidth(mContext);
        imageCarouselBanner.onInstance(mContext, urls, R.drawable.ad_show_indicator,
                new ImageCarouselBlogClickListener(mContext, (ArrayList<ImgItemsBean>) blog.getImgItems()));
    }
	
	@Override
	protected void callBeforeDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
        switch (information) {
            case BLOG_GET:
            case CLIENT_GET:
            case FOLLOW_COLLECT_SAVEOPERATE:
            case BLOG_LIST:
            case REPLY_LIST:
                showProgressDialog("请稍候");
                break;
        }
    }

	@Override
	protected void callAfterDataBack(HemaNetTask netTask) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
            case BLOG_GET:
            case CLIENT_GET:
            case FOLLOW_COLLECT_SAVEOPERATE:
            case BLOG_LIST:
            case REPLY_LIST:
                cancelProgressDialog();
                break;
        }
    }

	@Override
	protected void callBackForServerSuccess(HemaNetTask netTask,
			HemaBaseResult baseResult) {
		BaseHttpInformation information = (BaseHttpInformation) netTask
				.getHttpInformation();
		switch (information) {
            case BLOG_GET:
                HemaArrayResult<BlogDetail> bResult = (HemaArrayResult<BlogDetail>) baseResult;
                blog = bResult.getObjects().get(0);
                refreshlayout.refreshSuccess();
                String token = user == null ? "" : user.getToken();
                getNetWorker().clientGet(token, blog.getClient_id());//获取田家详细信息
                break;
            case CLIENT_GET:
                HemaArrayResult<ClientDetails> uResult = (HemaArrayResult<ClientDetails>) baseResult;
                client = uResult.getObjects().get(0);
                setData();
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");// 关联类型 1关注，2：收藏,3：点赞
                String oper = netTask.getParams().get("oper");// 操作	1添加 ，2取消 ;3：清空
                if (keytype.equals("2") && oper.equals("1")) {
                    XtomToastUtil.showShortToast(mContext, "添加收藏成功!");
                    titleLove.setImageResource(R.drawable.star_while);
                    blog.setCollectflag("1");
                } else if (keytype.equals("2") && oper.equals("2")) {
                    XtomToastUtil.showShortToast(mContext, "取消收藏成功!");
                    titleLove.setImageResource(R.drawable.star_while_stroke);
                    blog.setCollectflag("0");
                } else if (keytype.equals("3") && oper.equals("1")) {//点赞成功
                    selJournal.setGoodflag("1");
                    int goodcount = Integer.parseInt(selJournal.getGoodcount());
                    selJournal.setGoodcount((goodcount + 1) + "");
                    for (Blog item : journals) {
                        if (item.getId().equals(selJournal.getId())) {
                            item = selJournal;
                        }
                    }
                    View view = getLayoutInflater().inflate(R.layout.pop_zan,
                            null);
                    final PopupWindow pop = new PopupWindow(view, LayoutParams.MATCH_PARENT,
                            LayoutParams.MATCH_PARENT);
                    pop.setOutsideTouchable(true);
                    pop.setFocusable(true);
                    pop.setBackgroundDrawable(new BitmapDrawable());
                    pop.showAsDropDown(findViewById(R.id.title_text));
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            pop.dismiss();
                        }
                    }, 1000);
                    adapter.notifyDataSetChanged();
                } else if (keytype.equals("3") && oper.equals("2")) {//取消点赞成功
                    selJournal.setGoodflag("0");
                    int goodcount = Integer.parseInt(selJournal.getGoodcount());
                    if (goodcount > 0) {
                        selJournal.setGoodcount((goodcount - 1) + "");
                    }
                    for (Blog item : journals) {
                        if (item.getId().equals(selJournal.getId())) {
                            item = selJournal;
                        }
                    }
                    adapter.notifyDataSetChanged();
                }
                break;
            case BLOG_LIST:
                HemaPageArrayResult<Blog> jResult = (HemaPageArrayResult<Blog>) baseResult;
                if (jResult == null || jResult.getObjects() == null)
                    return;
                ArrayList<Blog> goods = jResult.getObjects();
                if (jouralPage == 0) {// 刷新
                    refreshlayout.refreshSuccess();
                    journals.clear();
                    journals.addAll(goods);
                } else {//加载更多
                    refreshlayout.loadmoreSuccess();
                    if (goods.size() > 0) {
                        journals.addAll(goods);
                    } else {
                        refreshlayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                adapter.setJournals(journals);
                refreshDatas(-1);
                break;
            case REPLY_LIST:
                HemaPageArrayResult<Reply> nResult = (HemaPageArrayResult<Reply>) baseResult;
                if (nResult == null || nResult.getObjects() == null)
                    return;
                ArrayList<Reply> replies = nResult.getObjects();
                if (replyPage == 0) {// 刷新
                    refreshlayout.refreshSuccess();
                    refreshlayout.setLoadmoreable(true);
                    this.replies.clear();
                    this.replies.addAll(replies);
                } else {// 更多
                    refreshlayout.loadmoreSuccess();
                    if (replies.size() > 0)
                        this.replies.addAll(replies);
                    else {
                        refreshlayout.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                adapter.setReplies(this.replies);
                refreshDatas(-1);
                break;
        }
    }

	@Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
                showTextDialog("获取商品信息失败！");
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                showTextDialog("操作失败\n请稍后再试");
                break;
            case BLOG_LIST:
                if (jouralPage == 0) {
                    refreshlayout.refreshFailed();
                } else {
                    refreshlayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "日志加载失败，" + baseResult.getMsg());
                break;
            case REPLY_LIST:
                if (replyPage == 0) {
                    refreshlayout.refreshFailed();
                } else {
                    refreshlayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "评论加载失败，" + baseResult.getMsg());
                break;
        }
    }

	@Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_GET:
                showTextDialog("获取商品信息失败！");
                titleText.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                showTextDialog("操作失败");
                break;
            case BLOG_LIST:
                if (jouralPage == 0) {
                    refreshlayout.refreshFailed();
                } else {
                    refreshlayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "日志加载失败，请稍后再试");
                refreshDatas(failedType);
                break;
            case REPLY_LIST:
                if (replyPage == 0) {
                    refreshlayout.refreshFailed();
                } else {
                    refreshlayout.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "评论加载失败，请稍后再试");
                refreshDatas(failedType);
                break;
        }
    }

    private void refreshDatas(int failed) {
        if (adapter == null) {
            adapter = new FarmerCropDetailAdapter(mContext, detailsImg, journals, replies, type);
            adapter.setItemClickListener(new OnJournalClickListener() {
                @Override
                public void OnItemClickListener(int position) {
                    if (type == 2) {//评论

                    }else if (type == 3) {//日志
                        Intent itBlog = new Intent(mContext, LaokeDetailActivity.class);
                        itBlog.putExtra("blog_id", journals.get(position).getId());
                        startActivity(itBlog);
                    }
                }

                @Override
                public void OnZanClickListener(final int position) {
                    if (type == 3) {//日志
                        loginCallBack = new LoginUtil.LoginCallBack() {
                            @Override
                            public void onLogin() {
                                selJournal = journals.get(position);
                                String operation = journals.get(position).getGoodflag();
                                if (operation.equals("0")) {
                                    operation = "1";//执行添加赞操作
                                }else {
                                    operation = "2";//取消赞
                                }
                                getNetWorker().FolColOperate(user.getToken(), "3", operation, journals.get(position).getId());
                                loginCallBack = null;
                            }
                        };
                        LoginUtil.getInstance(mContext, loginCallBack);
                    }
                }

                @Override
                public void OnCommentClickListener(final int position) {
                    if (type == 3) {//日志评论
                        loginCallBack = new LoginUtil.LoginCallBack() {
                            @Override
                            public void onLogin() {
                                Intent itComment = new Intent(mContext, ReleaseBlogActivity.class);
                                itComment.putExtra("type", 2);
                                itComment.putExtra("blog_id", journals.get(position).getId());
                                startActivity(itComment);
                                loginCallBack = null;
                            }
                        };
                        LoginUtil.getInstance(mContext, loginCallBack);
                    }else if (type == 2) {//回复别人的口碑评价
                        loginCallBack = new LoginUtil.LoginCallBack() {
                            @Override
                            public void onLogin() {
                                Intent itComment = new Intent(mContext, ReleaseBlogActivity.class);
                                itComment.putExtra("type", 3);
                                itComment.putExtra("blog_id", blog_id);
                                itComment.putExtra("reply", replies.get(position));
                                startActivity(itComment);
                                loginCallBack = null;
                            }
                        };
                        LoginUtil.getInstance(mContext, loginCallBack);
                    }
                }

                @Override
                public void OnDeleteClickListener(int position) {
                    if (type == 3) {//日志
                        Intent itBlog = new Intent(mContext, LaokeDetailActivity.class);
                        itBlog.putExtra("blog_id", journals.get(position).getId());
                        startActivity(itBlog);
                    }
                }
            });
            if (user != null &&user.getId().equals(blog.getClient_id())) {
                adapter.setOwner(true);
            }
            listView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        if (type == 1)
            adapter.setEmptyString("暂无图片介绍");
        else if (type == 2)
            adapter.setEmptyString("暂无评论");
        else if (type == 3)
            adapter.setEmptyString("暂无日志");
        adapter.setFailtype(failed);
    }
	
	@Override
	protected void setListener() {
		titleText.setText("商品详情");
        titleRightBtn.setVisibility(View.GONE);
        titleLove.setVisibility(View.VISIBLE);
        titleShare.setVisibility(View.VISIBLE);
        titleShare.setImageResource(R.drawable.share);
        titleLeft.setOnClickListener(this);
        titleLove.setOnClickListener(this);
        titleShare.setOnClickListener(this);
        tvCustomize.setOnClickListener(this);
        tvCustomize.setText("立即购买");
        refreshlayout.setOnStartListener(new XtomRefreshLoadmoreLayout.OnStartListener() {

            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout v) {
                String token = user == null?"":user.getToken();
                if (type == 2) {
                    replyPage = 0;
                    getNetWorker().replyList("2", blog_id, replyPage + "");
                }else if (type == 3) {
                    jouralPage = 0;
                    getNetWorker().blogList("7", blog_id, "5", "1", "", "", "", "", "", "", "", "", "", "", jouralPage + "");
                }else if (type == 1) {
                    getNetWorker().getBlogDetail(token, blog_id);
                }
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout v) {
                if (type == 2) {
                    replyPage++;
                    getNetWorker().replyList("2", blog_id, replyPage + "");
                }else if (type == 3) {
                    jouralPage++;
                    getNetWorker().blogList("7", blog_id, "5", "1", "", "", "", "", "", "", "", "", "", "", jouralPage + "");
                }else
                    refreshlayout.loadmoreSuccess();
            }
        });
	}
	
	private void setData() {
        String collectFlag = blog.getCollectflag();
        if (collectFlag == null || collectFlag.equals("0")) {
            titleLove.setImageResource(R.drawable.star_while_stroke);
        }else {
            titleLove.setImageResource(R.drawable.star_while);
        }
        tvGoodsName.setText(blog.getName());
        tvPriceNew.setText(blog.getPrice());
        tvPriceOld.setText("¥"+blog.getOldprice());
        tvPriceOld.getPaint().setFlags(Paint. STRIKE_THRU_TEXT_FLAG ); //中间横线
        tvAssort.setText(blog.getTypename());
        tvFreight.setText("运费："+blog.getExpressfee());
        tvUnit.setText("规格："+blog.getUnit());
        tvCouponsCount.setText(blog.getScore()+"粮票");
        tvSellCount.setText("销量"+blog.getSellcount()+"/库存"+blog.getLeftcount());
        //判断是否允许退货
        String returnflag = blog.getReturnflag();// 允许退货标记	0不允许 1允许
        tvTuihuo.setVisibility(View.VISIBLE);
        if (returnflag.equals("0")) {
            tvTuihuo.setText("拒绝退货");
            tvTuihuo.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_return_no, 0, 0, 0);
        }else {
            tvTuihuo.setText("允许退货");
            tvTuihuo.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_return, 0, 0, 0);
        }
        ImageUtils.loadAvatar(mContext, client.getAvatar(), ivMerchantAvatar);
        tvMerchantName.setText(client.getNickname());
        String star = client.getStarscore();
        if (!isNull(star)) {
            ratingBar.setRating(Float.parseFloat(star));
        }
        tvMerchantAddress.setText(client.getAddress());
        tvPackage.setText(blog.getContent());
        tvSpec.setVisibility(View.GONE);
        detailsImg.clear();
        detailsImg.addAll((ArrayList<ImgItemsBean>) blog.getImg2Items());
        initImagePager();
        //初始化第一页
        if (listView.getHeaderViewsCount() > 0) {
            listView.removeHeaderView(headerView);
            listView.removeHeaderView(headerView2);
        }
        listView.addHeaderView(headerView);
        listView.addHeaderView(headerView2);
        refreshDatas(-1);
	}
	
	@Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.title_right_img:
                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        String token = user.getToken();
                        if ("0".equals(blog.getCollectflag())) {//未关注
                            getNetWorker().FolColOperate(token, "2", "1", blog.getId());
                        } else {//已关注
                            getNetWorker().FolColOperate(token, "2", "2", blog.getId());
                        }
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.title_right_img2://分享
                String sys_plugins = getApplicationContext().getSysInitInfo().getSys_plugins();
                String username = user == null? "":user.getUsername();
                String path = sys_plugins + "share/sdk.php?id=" + blog_id + "&customflag=0&username="+username;
                //图片url
                UMImage image = null;
                String imgUrl = blog.getImgurl();
                if (!isNull(imgUrl)) {
                    image = new UMImage(mContext, imgUrl);
                } else {
                    imgUrl = BaseUtil.getLogoImagePath(mContext);
                    image = new UMImage(mContext, BitmapFactory.decodeFile(imgUrl));
                }
                new ShareDialog(FarmerCropDetailActivity.this, "分享商品", blog.getName(), path, image)
                        .builder().show();
                break;
            case R.id.iv_phone:
                final String phone = blog.getMobile();
                if (phone != null && !phone.isEmpty() && !phone.equals("无")) {
                    HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
                    hbDialog.setText("是否直接拨打" + phone + "?");
                    hbDialog.setLeftButtonText("取消");
                    hbDialog.setRightButtonText("拨打");
                    hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
                    hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

                        @Override
                        public void onLeftButtonClick(HemaButtonDialog dialog) {
                            dialog.cancel();
                        }

                        @Override
                        public void onRightButtonClick(HemaButtonDialog dialog) {
                            dialog.cancel();
                            Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(
                                    "tel:" + phone));
                            startActivity(intent);
                        }
                    });
                } else {
                    XtomToastUtil.showShortToast(mContext, "对方没有提供电话号码");
                }
                break;
            case R.id.tv_customize:
                if (blog.getSaleflag().equals("0")) {
                    XtomToastUtil.showShortToast(mContext, "商品已下架");
                    return;
                }
                loginCallBack = new LoginUtil.LoginCallBack() {
                    @Override
                    public void onLogin() {
                        if (user.getId().equals(blog.getClient_id())) {
                            showTextDialog("不能购买自己的商品!");
                            return;
                        }
                        int lefcount = 0;
                        try {
                            lefcount = Integer.parseInt(blog.getLeftcount());
                        }catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (lefcount > 0) {
                            Intent intent = new Intent(mContext, FarmerCropBuyActivity1.class);
                            intent.putExtra("blog", blog);
                            startActivity(intent);
                        }else
                            XtomToastUtil.showShortToast(mContext, "库存不足！");
                        loginCallBack = null;
                    }
                };
                LoginUtil.getInstance(mContext, loginCallBack);
                break;
            case R.id.layout_merchant:
                Intent itMerchant = new Intent(mContext, FarmerDetailsActivity.class);
                User user = BaseApplication.getInstance().getUser();
                if (user != null) {
                    String id = user.getId();
                    if (id.equals(blog.getClient_id())) {
                        itMerchant.setClass(mContext, MyFarmerActivity.class);
                    }
                }
                itMerchant.putExtra("client_id", blog.getClient_id());
                mContext.startActivity(itMerchant);
                break;
            case R.id.layout_detail:
                reset();
//                tvDetail.setTextColor(getResources().getColor(R.color.theme_orange));
                lineDetail.setVisibility(View.VISIBLE);
                listView.addHeaderView(headerView2);
                listView.setDividerHeight(BaseUtil.dip2px(mContext, 10));
                type = 1;
                adapter.setType(1);
                refreshDatas(-1);
                break;
            case R.id.layout_journal:
                reset();
//                tvJournal.setTextColor(getResources().getColor(R.color.theme_orange));
                lineJournal.setVisibility(View.VISIBLE);
                listView.removeHeaderView(headerView2);
                listView.setDividerHeight(BaseUtil.dip2px(mContext, 10));
                type = 3;
                adapter.setType(3);
                if (journals.size() == 0) {
                    getNetWorker().blogList("7", blog_id, "5", "1", "", "", "", "", "", "", "", "", "", "", jouralPage + "");
                }else
                    refreshDatas(-1);
                break;
            case R.id.layout_reply:
                reset();
//                tvReply.setTextColor(getResources().getColor(R.color.theme_orange));
                lineReply.setVisibility(View.VISIBLE);
                listView.removeHeaderView(headerView2);
                listView.setDividerHeight(0);
                type = 2;
                adapter.setType(2);
                if (replies.size() == 0) {
                    getNetWorker().replyList("2", blog_id, replyPage + "");
                }else
                    refreshDatas(-1);
                break;
        }
    }

    private void reset() {
//        tvDetail.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
        lineDetail.setVisibility(View.GONE);
//        tvJournal.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
        lineJournal.setVisibility(View.GONE);
//        tvReply.setTextColor(getResources().getColor(R.color.text_color_dark_grey));
        lineReply.setVisibility(View.GONE);
    }

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		UMShareAPI.get( this ).onActivityResult( requestCode, resultCode, data);
	}

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            if (loginCallBack != null)
                loginCallBack.onLogin();
        }else if (msg.getType() == EventBusConfig.UPDATE_REPLY_ADD
                || msg.getType() == EventBusConfig.UPDATE_REPLY_REMOVE) {
            refreshlayout.getOnStartListener().onStartRefresh(refreshlayout);
        }else if (msg.getType() == EventBusConfig.UPDATE_PRODUCTION) {
            if (!blog_id.equals("0")) {
                String token = user == null?"":user.getToken();
                getNetWorker().getBlogDetail(token, blog_id);
            }
        }
    }
}
